<?php

namespace app\shop\controller\plus;

use app\common\model\user\User;
use app\shop\controller\Controller;
use app\api\model\settings\Setting as SettingModel;
use app\shop\model\plus\sign\Sign as SignModel;

/**
 * Class Officia
 * 签到有礼控制器
 * @package app\shop\controller\plus\officia
 */
class Sign extends Controller
{

    private $days = [2, 3, 4, 5, 6, 7, 15, 30, 60];
    private $sign_date = [7, 15, 30];

    /**
     * 签到有礼配置
     */
    public function index()
    {
        $key = 'sign';
        if($this->request->isGet()){
            $vars['values'] = SettingModel::getItem($key);
            return $this->renderSuccess('', compact('vars'));
        }

        $model = new SettingModel;
        if ($model->edit($key, $this->postData())) {
            return $this->renderSuccess('操作成功');
        }
    }

    /**
     * 获取用户签到列表
     */
    public function lists()
    {
        $model = new SignModel;
        $list = $model->getList($this->postData(), $this->days, $this->sign_date);

        return $this->renderSuccess('', compact('list'));
    }

    /**审核 */
    public function check(){
        $data = $this->postData();
        if(empty($data['user_sign_id'])){
            return $this->renderError('参数错误');
        }
        $sign = SignModel::find($data['user_sign_id']);
        if(!$sign){
            return $this->renderError('参数错误');
        }
        if($sign->checker){
            return $this->renderError('已审核，不要重复操作');
        }
        $sign->startTrans();
        try{
            if($data['points']>0){
                $sign->points = $data['points'];
                $points_name = SettingModel::getPointsName();
                $sign->prize = $data['points'].$points_name;
                //赠送积分
                $user = User::detail($sign['user_id']);
                $user->setIncPoints($data['points'], '签到有礼'.$sign['sign_date']);
            }
            $sign->checker = $this->store['user']['shop_user_id'];
            $sign->save();
            $sign->commit();
            return $this->renderSuccess('操作成功');
        }catch (\Exception $e){
            $sign->rollback();
            return $this->renderError('操作失败');
        }
    }
}